package org.terracotta.toolkit.samples;

import org.terracotta.api.ClusteringToolkit;
import org.terracotta.api.TerracottaClient;
import org.terracotta.cluster.ClusterEvent;
import org.terracotta.cluster.ClusterInfo;
import org.terracotta.cluster.ClusterListener;

import java.net.UnknownHostException;

/**
 *  Sample Demo of the Cluster Events
 */
public class ClusteredEvents {

    // Handle to the toolkit
    ClusteringToolkit clusterToolkit = null;

    public void initializeToolKit(String serverAdd) {
        clusterToolkit = new TerracottaClient(serverAdd).getToolkit();
    }

    public void initializeClusterListener() {
        ClusterInfo clusterInfo = clusterToolkit.getClusterInfo();
        clusterInfo.addClusterListener(new MyClusterListener());
    }

    class MyClusterListener implements ClusterListener {

        public void nodeJoined(ClusterEvent clusterEvent) {
            try {
                System.out.println("Event Type = "+clusterEvent.getType());
                System.out.println("Node Joined "+clusterEvent.getNode().getId()
                        + ", IP="+clusterEvent.getNode().getAddress());
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }

        public void nodeLeft(ClusterEvent clusterEvent) {
            try {
                System.out.println("Node Left "+clusterEvent.getNode().getId()
                        + ", IP="+clusterEvent.getNode().getAddress());
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }

        public void operationsEnabled(ClusterEvent clusterEvent) {
            System.out.println("Operations Enabled");
        }

        public void operationsDisabled(ClusterEvent clusterEvent) {
            System.out.println("Operations Disabled");
        }
    }

    public static void main(String[] args) {
        ClusteredEvents clusterEventDemo = new ClusteredEvents();
        clusterEventDemo.initializeToolKit(args[0]);
        clusterEventDemo.initializeClusterListener();
        // Just to keep my program running
        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
